<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Models\Order;
use App\Models\ProceedList;
use App\Services\Facades\OrderService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class WechatPaymentController extends Controller
{
    // 处理支付回调
    public function handlePaymentCallback(Request $request)
    {
        // 处理回调
        $response = EasyWeChat::payment()->handlePaidNotify(function ($message, $fail) {
            Log::info($message);
            $proceedList = ProceedList::with(['order', 'user.runErrand'])->where('order_number', $message['out_trade_no'])->first();
            // 处理支付成功的逻辑
            // $message 包含了支付回调的所有信息
            // 例如:
            // $message['transaction_id'] // 微信支付订单号
            // $message['out_trade_no'] // 商户订单号
            // $message['total_fee'] // 订单金额
            // $message['cash_fee'] // 实收金额

            // 支付成功
            if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
                // TODO: 更新订单状态为支付成功
                Log::info('支付成功:', $message);
                // 订单支付成功逻辑
                $order = Order::where('order_number', $message['out_trade_no'])->first();
                if ($order && $order->status == 1) {
                    $order->status = 2;
                    $order->paid_at = now();
                    $order->save();
                }
                //跑腿接单支付成功逻辑
                if ($proceedList) {
                    $proceedList->status = 1;
                    $proceedList->save();
                    $proceedList->order->status = 5;
                    $proceedList->order->run_errand_id = $proceedList->user->runErrand->id;
                    $proceedList->order->save();
                }
                return true;
            } // 支付失败
            elseif ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'FAIL') {
                Log::info('支付失败:', $message);
                if ($proceedList) {
                    $proceedList->status = 3;
                    $proceedList->save();
                }
                // 返回错误信息给微信
                return false;
            }
        });
        return $response;
    }

    // 处理微信退款回调
    public function handleRefundCallback(Request $request)
    {

        // 处理回调
        $response = EasyWeChat::payment()->handleRefundedNotify(function ($message, $fail) {
            // 这里你可以处理退款通知，比如更新订单状态
            // $message 包含了退款回调的所有信息
            // 例如:
            // $message['transaction_id'] // 微信支付订单号
            // $message['out_trade_no'] // 商户订单号
            // $message['refund_id'] // 微信退款单号
            // $message['total_fee'] // 订单金额
            // $message['refund_fee'] // 退款金额

            // 例如更新数据库订单状态
            // $order = Order::where('out_trade_no', $message['out_trade_no'])->first();
            // if ($order) {
            //     $order->status = 'refunded';
            //     $order->save();
            // }

            // 返回成功消息
            return true; // 返回true表示成功
        });

        return $response; // 响应给微信
    }

    /*
     * 任务时间截止没有跑腿接单，自动取消订单，并退款
     * */
    public function refundOrder()
    {
        Order::with('user')->whereIn('status', [2, 3])->get()->map(function ($item) {
            if ($item->cut_off_at <= Carbon::now() && $item->amount >= 0.01) {
                //如果已经到任务截止时间，退款
                //如果任务有佣金，退回佣金
                try {
                    // 开始事务
                    DB::beginTransaction();
                    $item->status = 7;
                    $item->save();
                    //如果任务有佣金，退回佣金
                    $result = OrderService::refund($item->order_number, bcadd($item->amount, $item->handling_fee, 2), bcadd($item->amount, $item->handling_fee, 2), 2);
                    Log::info($result->content() ?? null);
                    // 提交事务
                    DB::commit();
                } catch (\Exception $e) {
                    // 发生错误，回滚事务
                    DB::rollBack();
                    // 处理异常
                    return ResponseHelper::error(message: $e->getMessage());
                }
            }
        });
        return ResponseHelper::success(message: '退款成功');
    }
}
